package com.cjl.multi_thread.old.threadpools;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class TestThreadLeakages {

    static class Task implements Runnable
    {
        private String name;

        public Task(String s)
        {
            name = s;
        }

        // Prints task name and sleeps for 1s
        // This Whole process is repeated 5 times
        public void run()
        {
            try
            {
                for (int i = 0; i<=5; i++)
                {
                    if (i==0)
                    {
                        Date d = new Date();
                        SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
                        System.out.println("Initialization Time for"
                                + " task name - "+ name +" = " +ft.format(d));
                        //prints the initialization time for every task
                    }
                    else
                    {
//                        if(name.equals("task 1")){
//                            throw new Exception();
//                        }

                            Date d = new Date();
                        SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
                        System.out.println("Executing Time for task name - "+
                                name +" = " +ft.format(d));
                        // prints the execution time for every task
                    }
                    Thread.sleep(1000);
                }
                System.out.println(name+" complete");
            }

            catch(InterruptedException e)
            {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        // creates five tasks
        Runnable r1 = new Task("task 1");
        Runnable r2 = new Task("task 2");
        Runnable r3 = new Task("task 3");
        Runnable r4 = new Task("task 4");
        Runnable r5 = new Task("task 5");

        ExecutorService pool = Executors.newScheduledThreadPool(3);

        // passes the Task objects to the pool to execute (Step 3)
        pool.execute(r1);
        pool.execute(r2);
        pool.execute(r3);
        pool.shutdown();
        if (pool.isShutdown()){
            pool = Executors.newScheduledThreadPool(3);
        }
        pool.execute(r4);
        pool.execute(r5);


        // pool shutdown ( Step 4)
        pool.shutdown();
//        List list = pool.shutdownNow();
//        System.out.println("TestThreadLeakages.main "+list.size());


    }
}
